package com.agent.vpsserver.common.config;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RemoteCommandExecutor {
    public static void main(String[] args) {
        String hostname = "120.78.74.63";
        String username = "root";
        String password = "Xn0MXJyw7VyupBvE";
        String command = "cat /var/log/squid/access.log | awk -v start_time=1709261880000 -v end_time=1709953080000 '{ gsub(\"\\\\.\", \"\", $1); if ($1 >= start_time && $1 <= end_time) sum[$8] += $5 } END { for (key in sum) print key, sum[key] }'";

        try {
            JSch jsch = new JSch();

            // 创建 SSH 会话
            Session session = jsch.getSession(username, hostname, 22);
            session.setPassword(password);

            // 忽略主机密钥检查
            session.setConfig("StrictHostKeyChecking", "no");

            // 连接 SSH 会话
            session.connect();

            // 打开 SSH 通道
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
//            ((ChannelExec) channel).setErrStream(System.err);

            // 获取命令执行结果
            InputStream inputStream = channel.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            // 连接 SSH 通道
            channel.connect();

            // 读取命令执行结果
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 关闭 SSH 通道和会话
            channel.disconnect();
            session.disconnect();

            // 输出执行结果
            System.out.println("Command Output:\n" + output.toString());

        } catch (JSchException | java.io.IOException e) {
            e.printStackTrace();
        }
    }
}